package com.crawleService.jinyeWebsite;

import com.crawleService.bean.JinyeConstant;
import com.google.gson.Gson;
import com.projectCommon.bean.Info;
import com.projectCommon.bean.cookie.JinyeCookie;
import com.projectCommon.bean.httpSmokeBean.jinyebean.Bean1;
import com.projectCommon.util.commonUtil.CUtil;
import com.projectCommon.util.commonUtil.JEncipherUtil;
import okhttp3.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.TimeZone;

public class test {

    public static void main(String[] args) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, IOException {
        login();
    }

    //    https://www.jinye.cn/cas/validUser  校验账号密码
    public static void login() throws NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, IOException, InvalidKeyException {
        createCaptcha();
        createCsrfToken_t();
        JEncipherUtil.currentAesEncipher(Info.password);
        OkHttpClient client = new OkHttpClient();
        Cookie cookie = new Cookie.Builder()
                .name("SESSION")
                .value(JinyeCookie.getSESSION())
                .domain("www.jinye.cn")
                .path("/cas/")
                .build();
        System.out.println("请输入验证码：");
        String next = new Scanner(System.in).nextLine();
        JinyeConstant.setVerifycode(next);
        RequestBody requestBody = new FormBody.Builder()
                .add("username", Info.userName)
                .add("password", JinyeConstant.getEncipherPassword())
                .add("verifycode", JinyeConstant.getVerifycode())
                .add("csrfToken", JinyeConstant.getCsrfToken_t())
                .build();
        Request request = new Request.Builder()
                .url("https://www.jinye.cn/cas/validUser")
                .header("Cookie", cookie.toString())
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                String s = CUtil.JsonFormatting(responseData);
                Gson gson = new Gson();
                Bean1 data = gson.fromJson(s, Bean1.class);
                String token = data.getToken();
                JinyeConstant.setToken(token);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        getTGT();
    }

    //    https://www.jinye.cn/cas/captcha.jpg  获取验证码  返回一个验证码的id和图片

    /**
     * 根据SESSION 返回一个 图片  并且得到对应的Session
     */
    public static void createCaptcha() {
        long modifiedTimestamp = System.currentTimeMillis() / 1000 * 1000; // 将后三位替换为0
        OkHttpClient client = new OkHttpClient();
        String url = "https://www.jinye.cn/cas/captcha.jpg" + "?id=" + modifiedTimestamp; // 替换为目标网址
        Cookie cookie = new Cookie.Builder()
                .name("SESSION")
                .value("234")
                .domain("www.jinye.cn")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .header("Cookie", cookie.toString())
                .build();
        try {
            Response response = client.newCall(request).execute();
            ByteArrayInputStream bis = new ByteArrayInputStream(response.body().bytes());
            BufferedImage image = ImageIO.read(bis);
            // 保存图片到本地文件
            File output = new File("jinye.jpg");
            ImageIO.write(image, "jpg", output);
            bis.close();
            System.out.println("验证码保存成功");
            if (response.isSuccessful()) {
                Headers headers = response.headers();
                List<String> values = headers.values("Set-Cookie");
                if (values.size() != 1) {
                    throw new RuntimeException("没有得到cookie");
                }
                for (String session : headers.values("Set-Cookie")) {
                    String[] split = session.split(";");
                    String[] split1 = split[0].split("=");
                    String s = split1[1];
                    JinyeCookie.setSESSION(s);
                }
            } else {
                System.out.println("Request failed");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取跨域的 csrfToken_t  的value
     * https://www.jinye.cn/cas/login?service=https%3A%2F%2Fwww.jinye.cn%2Fmarketing-orderplatform%2Fcascallback
     */
    public static void createCsrfToken_t() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://www.jinye.cn/cas/login?service=https%3A%2F%2Fwww.jinye.cn%2Fmarketing-orderplatform%2Fcascallback")
                .build();
        try {
            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                String string = response.body().string();
                Document document = Jsoup.parse(string);
                Element execution = document.select("input[name=execution]").first();
                JinyeConstant.setExecution(execution.attr("value"));
                Element csrfTokenInput = document.select("input[name=csrfToken_t]").first();
                // 获取input输入框的值
                if (csrfTokenInput != null) {
                    JinyeConstant.setCsrfToken_t(csrfTokenInput.attr("value"));
                }
            } else {
                System.out.println("Request failed");
            }
            String date1 = response.header("Date");
//            Sun, 31 Mar 2024 02:20:01 GMT
            String[] s = date1.split(" ");
            String s1 = s[3] + "-" + "3-31 " + s[4];
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date date = sdf.parse(s1);
            // 将时间转换为北京时间（GMT+8）
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            String beijingTime = sdf.format(date);
            System.out.println("北京时间：" + beijingTime);
            long time = date.getTime();
            long l = System.currentTimeMillis();
            System.out.println("时间戳：" + date.getTime());
            JinyeConstant.setTime(time + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * cas/login
     */
    public static void getTGT() throws IOException {
        OkHttpClient client = new OkHttpClient();
//        https://www.jinye.cn/cas/login?_t=1711844032394
        long l = System.currentTimeMillis() - 1000 * 20;
        String url = "https://www.jinye.cn/cas/login?_t=" + JinyeConstant.getTime() + 655; // 替换为目标网址
        Cookie cookie1 = new Cookie.Builder()
                .name("SESSION")
                .value(JinyeCookie.getSESSION())
                .path("/cas/")
                .domain("www.jinye.cn")
                .build();
        Cookie cookie2 = new Cookie.Builder()
                .name("usercode")
                .value(JinyeCookie.getUsercode())
                .path("/")
                .domain("www.jinye.cn")
                .build();
        Cookie cookie3 = new Cookie.Builder()
                .name("pk_corp")
                .value(JinyeCookie.getPk_corp())
                .path("/")
                .domain("www.jinye.cn")
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("username", Info.userName)
                .add("yytpasspword", "")
                .add("password", JEncipherUtil.urlEncode(JinyeConstant.getEncipherPassword()))
                .add("loginBeforeEnableSetPkcorp", "true")
                .add("execution", JinyeConstant.getExecution())
                .add("_eventId", "submit")
                .add("geolocation", "")
                .add("md5pwd", JEncipherUtil.urlEncode(JinyeConstant.getEncipherPassword()))
                .add("csrfToken_t", JEncipherUtil.urlEncode(JinyeConstant.getCsrfToken_t()))
                .add("isNeedVerifyCode", "true")
                .add("token", JinyeConstant.getToken())
                .add("defaultPkCorp", "0")
                .add("pk_corp", "0001")
                .add("cipherText", "")
                .add("plainText", "")
                .add("csrfToken", JEncipherUtil.urlEncode(JinyeConstant.getCsrfToken_t()))
                .add("submit", JEncipherUtil.urlEncode("登录中..."))
                .build();
        FormBody formBody = (FormBody) requestBody;
        for (int i = 0; i < formBody.size(); i++) {
            System.out.println(formBody.name(i) + "=" + formBody.value(i));
        }
        long contentLength = requestBody.contentLength();
        System.out.println("请求体长度为：" + contentLength);

        Request request = new Request.Builder()
                .url(url)
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
//                .header("Accept-Encoding", "gzip, deflate, br, zstd")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                //TODO:   会不会是检测这个是否相等呢？？
                .header("Content-Length", contentLength + "")
                .header("Content-Type", "application/x-www-form-urlencoded")
                //TODO:  核对一下这个字段
                .header("Cookie", cookie1.toString() + "; " + cookie2.toString() + "; " + cookie3.toString())

                .header("Host", "www.jinye.cn")
                .header("Origin", "https://www.jinye.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "https://www.jinye.cn/cas/login?service=https%3A%2F%2Fwww.jinye.cn%2Fmarketing-orderplatform%2Fcascallback")
                .header("Sec-Ch-Ua", "\"Google Chrome\";v=\"123\", \"Not:A-Brand\";v=\"8\", \"Chromium\";v=\"123\"")
                .header("Sec-Ch-Ua-Mobile", "?0")
                .header("Sec-Ch-Ua-Platform", "\"Windows\"")
                .header("Sec-Fetch-Dest", "document")
                .header("Sec-Fetch-Mode", "navigate")
                .header("Sec-Fetch-Site", "same-origin")
                .header("Sec-Fetch-User", "?1")
                .header("Upgrade-Insecure-Requests", "1")
                .header("User-Agent",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .post(requestBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
            Headers headers = response.headers();
            String s = headers.toString();
            System.out.println(s);
            List<String> values = response.headers().values("Set-Cookie");
            if (values.size() != 0) {
                System.out.println("有戏");
            } else {
                System.out.println("无戏");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test1() {
//        这几个请求挨着看，四五个请求，  从验证码开始！！  应该可以破解
        createCaptcha();

    }
    @Test
    public void test2(){
        String s = JEncipherUtil.urlEncode("T4X3L3qN1T+N0v8UjDKvUw==");
        System.out.println(s);
    }
}
